package com.sky.config;

import cn.hutool.core.util.IdUtil;
import com.sky.constant.AuthConstant;
import com.sky.constant.CartConstant;
import com.sky.dto.member.UmsMemberVO;
import com.sky.to.LoginMemberTo;
import com.sky.utils.StringUtils;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.util.Objects;

public class CartInterceptor implements HandlerInterceptor {

    public static ThreadLocal<LoginMemberTo> threadLocal = new ThreadLocal<>();
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        LoginMemberTo loginMemberTo = new LoginMemberTo();

        // 获取临时用户的cookie中的userKey
        Cookie[] cookies = request.getCookies();
        if (StringUtils.isNotEmpty(cookies)){
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals(CartConstant.CART_USER_KEY)){
                    String value = cookie.getValue();
                    loginMemberTo.setUserKey(value);
                }
            }
        }
        if (StringUtils.isEmpty(loginMemberTo.getUserKey())){
            // 临时用户key不存在，生成一个
            String userKey = IdUtil.fastUUID();
            loginMemberTo.setUserKey(userKey);
            loginMemberTo.setTempUser(true);
        }
        // 获取登录用户的用户id
        UmsMemberVO umsMemberVO = (UmsMemberVO)request.getSession().getAttribute(AuthConstant.SESSION_USER_INFO);
        if (Objects.nonNull(umsMemberVO)){
            // 用户已经登录
            loginMemberTo.setUserId(umsMemberVO.getId());
        }

        threadLocal.set(loginMemberTo);

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        LoginMemberTo loginMemberTo = threadLocal.get();
        if (loginMemberTo.isTempUser()){
            // 将临时用户key写入cookie
            Cookie cookie = new Cookie(CartConstant.CART_USER_KEY, loginMemberTo.getUserKey());
            cookie.setDomain(AuthConstant.PROJECT_PARENT_DOMAIN_NAME);
            cookie.setPath(AuthConstant.PROJECT_PARENT_COOKIE_PATH);
            cookie.setMaxAge(CartConstant.CART_USER_KEY_TIME_OUT);
            response.addCookie(cookie);
        }
    }
}
